﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Collections;

namespace Storytelling.Utils
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
    public class ArrayRangeAttribute : ValidationAttribute
    {
        private int minimum;
        private object obj;

        public ArrayRangeAttribute(int minimum)
        {
            this.minimum = minimum;
        }

        public ArrayRangeAttribute(int minimum, object obj)
        {
            this.minimum = minimum;
            this.obj = obj;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return base.IsValid(value, validationContext);
        }

        public override bool IsValid(object value)
        {
            Array array = value as Array;

            if (array == null)
            {
                return false;
            }

            bool isValid = array.Length >= minimum;

            if (obj != null)
            {
                foreach (var item in array)
                {
                    if (obj.Equals(item))
                    {
                        isValid = false;
                        break;
                    }
                } 
            }

            return isValid;
        }
    }
}
